using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AXBC = Microsoft.Dynamics.BusinessConnectorNet;
using AXMD = Microsoft.Dynamics.Framework.Metadata.Ax;
using Proxy = Microsoft.Dynamics.Framework.BusinessConnector.Proxy;

namespace DynamicsAXPS
{
    [System.Management.Automation.Cmdlet("Get", "AXDataSetDataEx")]
    public class Get_AXDataSetDataEx : System.Management.Automation.PSCmdlet
    {
        [System.Management.Automation.Parameter(Position = 0, Mandatory = true)]
        public string DataSet;

        protected override void ProcessRecord()
        {

            // http://blogs.msdn.com/b/epblog/archive/2008/08/21/managed-dataset-part-2.aspx

            var ds = DynamicsAXUtil.AXDataUtil.GetAXDataSetData(this.DataSet);
            var md = ds.Metadata;

            // Construct Data Table


            var dt = new System.Data.DataTable();
            foreach (var v in md.DataSetViews)
            {
                var fields = v.ViewFields;
                foreach (var f in fields)
                {
                    var col = dt.Columns.Add(f.Name, f.DataType);
                }
            }

            int num_rows_in_page = ds.DataSetViews[0].Count;

            this.WriteVerbose(string.Format("Num Rows in Page: {0}", num_rows_in_page));
            this.WriteVerbose(string.Format("Num Total Rows: {0}", ds.DataSetViews[0].GetTotalNumberOfRows()));
            this.WriteVerbose(string.Format("Num Views: {0}", ds.DataSetViews.Count));

            int num_cols = dt.Columns.Count;
            var objarray = new object[num_cols];

            // Add a bunch of empty rows
            for (int row_index = 0; row_index < num_rows_in_page; row_index++)
            {
                int ci = 0;

                foreach (var view in ds.DataSetViews)
                {
                    var viewlist = (System.Collections.IList)view;
                    Microsoft.Dynamics.Framework.Data.Ax.DataSetViewRow crow = (Microsoft.Dynamics.Framework.Data.Ax.DataSetViewRow)viewlist[row_index];

                    for (int xci = 0; xci < view.Metadata.ViewFields.Count; xci++)
                    {
                        var ct_col = dt.Columns[ci];
                        var col_value = crow.GetFieldValue(ct_col.ColumnName);
                        objarray[ci] = col_value;
                        ci++;
                    }

                }

                dt.Rows.Add(objarray);
            }

            this.WriteObject(dt);
        }
    }
}
